<template>
    <div class="app-container">
        <el-row class="marginBottom10">
            <el-col :span="24" style="font-weight: 600;">订单号：{{rowData.orderNo}}--{{_stepStatus}}</el-col>
        </el-row>
        <!-- <Steps :status="_stepStatus" :invoiceStatus="rowData.invoiceStatus" :businessRoleEnum="businessRoleEnum" :cancellationStatus="_cancellationStatus" :frontNodeReviewStatus="_frontNodeReviewStatus" :currentNodeType="_currentNodeType"  :remark="rowData.remark" :payStatus="rowData.payStatus"></Steps> -->
        <el-card>
            <StepsTool :status="_stepStatus" :orderData="rowData" :businessRoleEnum="businessRoleEnum"></StepsTool>
        </el-card>
        <el-card class="marginTop10" style="position: relative;">
            <h4>{{ rowData.companyName }}</h4> 
            <Signature class="signature-position" :status="_stepStatus" :currentNodeType="_currentNodeType" :businessRoleEnum="businessRoleEnum"  ></Signature>
            <el-row gutter="10">
                <el-col :span="8" >
                    <Carousel v-bind="swiperData"></Carousel>
                </el-col>
                <el-col :offset="1" :span="15">
                    <el-row justify="start" align="middle">
                        <el-col :span="20">
                            <div class="city-title text-ellipsis">{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</div>
                            <!-- <div class="city-content text-ellipsis">购箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</div> -->
                        </el-col>
                    </el-row>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="2">单价:</el-col>
                        <el-col :span="15">
                            <template v-if="_stepStatus < 3">
                                <template v-if="sourceType == 'edit'">
                                    <el-input v-model="rowData.unitPrice" style="max-width: 250px" class="input-with-select">
                                        <template #prepend>
                                            <el-select v-model="rowData.currency" placeholder="Select" style="width: 70px;color: #ff0000;">
                                                <el-option label="$" value="USD" />
                                                <el-option label="￥" value="CNY" />
                                            </el-select>
                                        </template>
                                    </el-input>
                                </template>
                                <template v-if="sourceType == 'view'">{{basicConfig.currency2[rowData.currency]}}{{rowData.unitPrice}}</template>
                            </template>
                            <template v-else>{{basicConfig.currency2[rowData.currency]}}{{rowData.unitPrice}}</template>
                        </el-col>
                    </el-row>
                    <el-divider border-style="dashed"/>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="8">箱型：{{basicConfig.boxTypeInfo1[rowData.boxType]}} </el-col>
                        <el-col :span="8">箱况： {{basicConfig.boxConditionInfo2[rowData.boxCondition]}} </el-col>
                        <el-col :span="8">联系人： {{rowData.contacts}}</el-col>
                        <el-col :span="8" class="marginTop20">联系电话 ：+{{rowData.agentUserAreaCode}} {{rowData.tel}}</el-col>
                    </el-row>
                    <el-divider  border-style="dashed"/>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="1">数量:</el-col>
                        <el-col :span="5">
                            <template v-if="_stepStatus < 3">
                                <template v-if="sourceType == 'edit'">
                                    <el-input-number v-model="rowData.boxQuantity" :min="1" :max="9999" />
                                </template>
                                <template v-if="sourceType == 'view'">{{rowData.boxQuantity}}个</template>
                            </template>
                            <template v-else>{{rowData.boxQuantity}}个</template>
                        </el-col>
                    </el-row>
                    <el-row  class="marginTop20" justify="start" align="middle">
                        <el-col :span="2">总额:</el-col>
                        <el-col :span="15" class="total">{{basicConfig.currency2[rowData.currency]}} {{ total }}</el-col>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="marginTop20 marginBottom20">
            <span class="_before">订单信息</span>
            <el-row class="marginTop20" justify="start" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span>预计提箱日期：</span></el-col>
                <el-col :span="6">
                    <template v-if="_stepStatus < 3 && businessRoleEnum == '10'">
                        <el-date-picker v-model="rowData.planPickupDate" type="date" placeholder="提箱日期" />
                    </template>
                    <template v-else>
                        {{formatDate(rowData.planPickupDate,2)}}
                    </template>
                </el-col>
                <el-col :span="2" class="text-right"><span>支付方式：</span></el-col>
                <el-col :span="6">
                    <template v-if="_stepStatus < 3">
                        <template v-if="sourceType == 'edit'">
                            <el-select v-model="paymentMethod" style="width:200px">
                                <el-option label="对公转账" value="5"/>
                                <el-option label="在线支付" value="10"/>
                            </el-select>
                        </template>
                        <template v-if="sourceType == 'view'">{{basicConfig.paymentMethod[paymentMethod]}}</template>
                    </template>
                    <template v-else>{{basicConfig.paymentMethod[paymentMethod]}}</template>
                </el-col>
                <el-col :span="2" class="text-right"><span>发票类型：</span></el-col>
                <el-col :span="5">
                    {{basicConfig.invoiceType[rowData.invoiceType]}}
                </el-col>
                <el-col :offset="1" :span="2" class="text-right marginTop20"><span>结算账期：</span></el-col>
                <el-col :span="20" class="marginTop20">
                    <template v-if="_stepStatus < 3"> 
                        <template v-if="sourceType == 'edit'">
                            <el-input v-model="rowData.period" placeholder="请输入天数" style="width:200px">
                                <template #append>天</template>
                            </el-input>
                        </template>
                        <template v-if="sourceType == 'view'">{{rowData.period}}天</template>
                    </template>
                    <template v-else>{{rowData.period}}天</template>
                </el-col>
                <!-- <el-col :offset="1" :span="2" class="text-right marginTop20"><span>箱号：</span></el-col> -->
                <!-- <el-col :span="20" class="marginTop20">
                    <template v-if="_stepStatus < 3 && businessRoleEnum == '10'">
                        <el-input v-model="param.containerNo" :rows="5" type="textarea" placeholder="请输入箱号（每个箱号之间适用'/'隔开）"/>
                    </template>
                    <template v-else>
                        {{rowData.containerNo || "--"}}
                    </template>
                </el-col> -->
            </el-row>
            <el-divider  border-style="dashed"/>
            <el-row class="marginBottom20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span>经办人：</span></el-col>
                <el-col :span="3">
                    <template v-if="businessRoleEnum == '10'">{{rowData.boxEastUserName}}</template>  <!--卖箱-->
                    <template v-else-if="businessRoleEnum == '5'">{{rowData.agentUserName}}</template> <!--买箱-->
                    <template v-else>--</template>
                </el-col>
                <template v-if="businessRoleEnum == '10'">
                    <el-col :offset="1" :span="2" class="text-center"><span>操作员:</span></el-col>
                    <template v-if="_stepStatus < 3">
                        <el-col :span="3">
                            <el-select v-model="param.boxEastOperatorUserId" filterable>
                                <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                            </el-select>
                        </el-col>
                    </template>
                    <template v-else>{{rowData.boxEastOperatorUserName}}</template>
                </template>
            </el-row>
            <template v-if="businessRoleEnum == '5'">
                <el-row v-for="(item,index) in allocation" :key="index" align="middle" class="marginBottom10">
                    <el-col :offset="1" :span="2" class="text-right"><span>业务员：</span></el-col> 
                    <el-col :span="5">{{item.businessUserName}}</el-col>
                    <el-col :offset="1" :span="2" class="text-right"><span>操作员：</span></el-col>
                    <el-col :span="5">{{item.operateUserName}}</el-col>
                    <el-col :offset="1" :span="2" class="text-right"><span>业务编号：</span></el-col>
                    <el-col :span="4">{{item.businessNo}}</el-col>
                </el-row>
            </template>
            
            <el-divider  border-style="dashed"/>
            <el-row>
                <el-col :offset="1" :span="2" class="text-right"><span>留言：</span></el-col>
                <el-col :span="20">{{rowData.leaveMsg || "--"}}</el-col>
            </el-row>
        </el-card>
        <template v-if="_stepStatus == 40">
            <el-card class="marginTop20" >
                <span class="_before">取消订单信息</span>
                <el-row justify="center" align="middle">
                    <el-col :span="24" class="text-center marginTop20 marginBottom20">取消原因：{{rowData.remark}}</el-col>
                    <template v-if="_cancellationStatus > 3">
                        <template v-if="rowData.canceledType == '5'"> 
                            <template v-if="businessRoleEnum == '5'"> <!-- 5：买箱确认 10：卖箱-->
                                <template v-if="_currentNodeType != 15">
                                    <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">拒绝</el-button></el-col>
                                    <el-col :span="3" @click="approved" class="text-center"><el-button type="danger">同意</el-button></el-col>
                                </template>
                            </template>

                            <template v-if="businessRoleEnum == '10'"> <!--谁发起取消 拒绝之后 谁确认-->
                                <template v-if="_currentNodeType == 15">
                                    <el-col :span="3" @click="approved(2)" class="text-center"><el-button type="warning">确认</el-button></el-col>
                                </template>
                            </template> 
                        </template>
                        <template v-if="rowData.canceledType == '10'"> <!--货代取消 -->
                            <template v-if="businessRoleEnum == '10'"> <!--箱东确认-->
                                <template v-if="_currentNodeType == 15">
                                    <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">确认</el-button></el-col>
                                </template>
                                <template v-else>
                                    <el-col :span="3" @click="rejected" class="text-center"><el-button type="warning">拒绝</el-button></el-col>
                                    <el-col :span="3" @click="approved" class="text-center"><el-button type="danger">同意</el-button></el-col>
                                </template>
                            </template>
                            <template v-if="businessRoleEnum == '5'"> <!--谁发起取消 拒绝之后 谁确认-->
                                <template v-if="_currentNodeType == 15">
                                    <el-col :span="3" @click="approved(2)" class="text-center"><el-button type="warning">确认</el-button></el-col>
                                </template>
                            </template> 
                        </template>
                    </template>
                </el-row>
            </el-card>
        </template>
        
        <!-- 取消订单  申请发票  确认订单 签署  开提箱单-->
        <template v-if="_stepStatus < 30"> 
            <el-affix v-if="_stepStatus < 30" position="bottom">
                <el-card>
                    <el-row align="middle" justify="center">
                        <el-col :span="24" v-if="_stepStatus == 2 && businessRoleEnum == '10'" class="text-center"> 
                            <el-checkbox v-model="radioView" size="large" />我已阅读<a style="color: #2020eb;" href="#">《集装箱租赁业务规则》</a><a style="color: #2020eb;" href="#">《用户服务协议和管理规则》</a>并同意全部条款
                        </el-col>
                        <el-col :span="2" v-if="_stepStatus < 30"><el-button type="warning" @click="toCancelOrder">取消订单</el-button></el-col>
                        <template v-if="_stepStatus == 2 && businessRoleEnum == '10'">
                            <el-col :span="2"><el-button type="primary" @click="confirmOrder">确认订单</el-button></el-col>
                        </template>
                        <template v-if="_stepStatus == 3">
                            <el-col :span="2"><el-button type="primary" @click="signContract">签署</el-button></el-col>
                            <template v-if="businessRoleEnum == '10'">
                                <el-col :span="2"><el-button type="primary" @click="completeSigning(rowData.id)">完成签署</el-button></el-col>
                            </template>
                        </template>
                        <template  v-if="businessRoleEnum == '10'">
                            <template v-if="_stepStatus == 20">
                                <el-col :span="2"><el-button type="primary" @click="handlePacking">开提箱单</el-button></el-col>
                            </template>
                        </template>
                        <!-- <template v-if="businessRoleEnum == '5'" >
                            <template v-if="_stepStatus > 3 && rowData.invoiceStatus == '5'">
                                <el-col :span="2"><el-button type="primary" @click="invoiceDialog = true">申请发票</el-button></el-col>
                            </template>
                        </template> -->
                    </el-row>
                </el-card>
            </el-affix>
        </template>



        <el-dialog v-model="eqbDialog" width="90%" :with-header="false" @close="closeEQianBao">
            <iframe v-if="eqbDialog" :src="eqbUrl" width="100%" height="750px" frameborder="0"></iframe>
        </el-dialog>

         <!-- 开提箱单 -->
        <el-dialog v-model="dackingDialog" :show-close="false" size="40%" :with-header="false"> 
            <el-row>
                <el-col :span="6">
                    <span class="_before">开提箱单</span>
                </el-col>
            </el-row>
            <el-row align="middle">
                <el-col :span="23" class="marginTop20">
                    <el-row>
                        <el-col :span="12">售箱订单：</el-col>
                        <el-col :span="12" class="text-right">
                            <el-button type="primary" :icon="Edit" size="small" @click="getOrderList">选择订单</el-button>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :offset="1" :span="22" class="marginTop10">
                    <el-table :data="packingListData" border style="width: 100%" >
                        <el-table-column prop="orderNo" label="订单号" align="center"/>
                        <el-table-column prop="planPickupDate" label="预计提箱日期" align="center">
                            <template #default="scope">{{formatDate(scope.row.planPickupDate,2)}}</template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="下单日期" align="center">
                            <template #default="scope">{{formatDate(scope.row.createTime,2)}}</template>
                        </el-table-column>
                    </el-table>
                </el-col>
                <el-row class="marginTop20">
                    <el-col :span="6">箱型/箱况/箱量</el-col>
                    <el-col :offset="1" :span="22" class="marginTop10">
                        <el-table :data="packingBoxType" border style="width: 100%" >
                            <el-table-column prop="boxType" label="箱型" align="center">
                                <template #default="scope">{{basicConfig.boxTypeInfo1[scope.row.boxType]}}</template>
                            </el-table-column>
                            <el-table-column prop="boxCondition" label="箱况" align="center">
                                <template #default="scope">{{basicConfig.boxConditionInfo2[scope.row.boxCondition]}}</template>
                            </el-table-column>
                            <el-table-column prop="boxQuantity" label="箱量" align="center"></el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="width: 100%;" class="marginTop20">
                    <el-col :span="6" class="_asterisk">提箱单有效期范围</el-col>
                    <el-col :offset="1" :span="22" class="marginTop10">
                        <el-date-picker v-model="packingValidityPeriod" type="daterange" range-separator="~" start-placeholder="开始时间" end-placeholder="截至时间"/>
                    </el-col>
                </el-row>
                <el-row class="marginTop20" style="width: 100%;">
                    <el-col :span="6">提箱单附件</el-col>
                    <el-col :offset="1" :span="22" class="marginTop10">
                        <ImgUpload ref="packingRef" :displayType="2" :urlList="fileList" :limit="10" :showNumber="6" :drag="true" :type="'jpg/png/jpeg/pdf'" />
                    </el-col>
                </el-row>
            </el-row>
            <el-row  class="marginTop30">
                <el-col :span="6">备注：</el-col>
                <el-col :offset="1" :span="22">
                    <el-input v-model="packingRemark" :rows="5" type="textarea" maxlength="1000" show-word-limit placeholder="请输入备注信息"/>
                </el-col>
            </el-row>
            <el-row justify="center" align="middle" class="marginTop30">
                <el-col :span="3" class="text-center"><el-button type="primary" @click="submitPicking">提交</el-button></el-col>
            </el-row>
        </el-dialog>
        <!-- 订单列表 -->
        <el-dialog v-model="orderListDialog" :show-close="false" size="30%" :with-header="false">
            <el-row>
                <el-col :span="6">
                    <span class="_before">订单列表</span>
                </el-col>
            </el-row>
            <el-row>
                <el-col :offset="1" :span="22">
                    <el-table :data="orderListInfo" @selection-change="handleSelectionChange" style="width: 100%">
                        <el-table-column type="selection" width="55" align="center"/>
                        <el-table-column prop="orderNo" label="订单号" width="200" align="center"/>
                        <el-table-column prop="planPickupDate" label="预计提箱日期" width="180" align="center">
                            <template #default="scope">
                                {{formatDate(scope.row.planPickupDate,2)}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="下单日期" align="center">
                            <template #default="scope">
                                {{formatDate(scope.row.createTime,2)}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="packingAllocationQuantity" label="已开箱量" align="center"/>
                        <el-table-column prop="weikaiQuantity" label="未开箱量" align="center">
                            <template #default="scope">{{scope.row.boxQuantity - scope.row.packingAllocationQuantity}}</template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row justify="center" class="marginTop20">
                <el-col :offset="20" :span="3" class="text-center"><el-button type="primary" @click="submitOrderInfo">确认</el-button></el-col>
            </el-row>
        </el-dialog>
        <!-- 申请发票 -->
        <el-dialog v-model="invoiceDialog" :show-close="false" size="40%" :with-header="false">
            <span class="_before">申请发票</span>
            <invoiceTemplate style="margin-top: 10px;"></invoiceTemplate>
            <el-row class="marginTop20">
                <el-col :span="6" class="text-right marginTop10">发票状态</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ { 5: '未申请', 10: '待开票', 15: '已开票' }[rowData.invoiceStatus] }}</el-col>
                <el-col :span="6" class="text-right marginTop10">发票内容</el-col><el-col :offset="5" :span="10" class="marginTop10">购箱明细</el-col>
                <el-col :span="6" class="text-right marginTop10">发票抬头</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ rowData.invoiceTitle }}</el-col>
                <!-- <el-col :span="6" class="text-right marginTop10">发票号码</el-col><el-col :offset="5" :span="10" class="marginTop10">{{ rowData.invoiceNo }}</el-col> -->
                <el-col :span="6" class="text-right marginTop10">联系人</el-col><el-col :offset="5" :span="10" class="marginTop10">+{{rowData.agentUserAreaCode}} {{rowData.tel}}</el-col>
                <el-col :span="6" class="text-right marginTop10">在线咨询</el-col><el-col :offset="5" :span="10" class="marginTop10">联系客服</el-col>
            </el-row>
            <el-form ref="invoiceRef" :model="rowData" v-if="rowData.invoiceStatus == '5'" label-width="auto" :rules="rules" style="margin-top: 30px;">
                <el-form-item label="发票类型" prop="invoiceType">
                    {{basicConfig.invoiceType[rowData.invoiceType]}}
                </el-form-item>
                <el-form-item label="企业名称" prop="invoiceTitle">
                    <el-input v-model="rowData.invoiceTitle" type="textarea" style="width: 500px;" maxlength="200" show-word-limit rows="1" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="统一社会信用代码" prop="invoiceTaxNum">
                    <el-input v-model="rowData.invoiceTaxNum" type="textarea" style="width: 500px;" maxlength="18" rows="1" placeholder="请输入统一社会信用代码"></el-input>
                </el-form-item>
                <!-- <el-form-item v-if="rowData.invoiceStatus == 5">
                    <el-button @click="handleApplyInvoice" type="primary" style="margin-top: 40px;text-align: right;">提交</el-button>
                </el-form-item> -->
                <el-row justify="center" align="middle">
                    <el-button @click="applyInvoice" type="primary" >提交</el-button>
                </el-row>
            </el-form>
            <!-- <iframe v-if="rowData.invoiceStatus == 15 && param.invoiceUrl && param.invoiceUrl.length > 0 && param.invoiceUrl[0].url"
                style="width:100%;height: auto;min-height: 400px;" :src="param.invoiceUrl[0].url + '#toolbar=0'">
            </iframe> -->
        </el-dialog>
        <!-- 查看提箱单 -->
        <!-- 查看提箱单列表 -->
        <el-dialog v-model="packingListDialog" title="提箱单列表">
            <el-table :data="packingListInfo" header-align="center" >
                <el-table-column property="packingNo" label="提箱单号" align="center">
                <template #default="scope">
                    <el-button link type="primary" size="default" @click.prevent="showPacking(scope.row)" >{{scope.row.packingNo}}</el-button>
                </template>
                </el-table-column>
                <el-table-column property="yardName" label="堆场名称" width="120" align="center"/>
                <el-table-column property="boxCondition" label="箱况" width="60" align="center"><!--箱况:boxCondition 5-全新   10-次新  15-适货 20-混提-->
                <template #default="scope">
                    <template v-if="scope.row.boxCondition == 5">全新</template>
                    <template v-if="scope.row.boxCondition == 10">次新</template>
                    <template v-if="scope.row.boxCondition == 15">适货</template>
                    <template v-if="scope.row.boxCondition == 20">混提</template>
                    <template v-else>--</template>
                </template>
                </el-table-column>
                <el-table-column property="residuePackingDays" label="剩余提箱天数" width="110" align="center">
                <template #default="scope">
                    {{scope.row.residuePackingDays}}天
                </template>
                </el-table-column>
                <el-table-column property="packingValidityPeriodStart" label="提箱单有效期范围" align="center">
                <template #default="scope">
                    {{ scope.row.packingValidityPeriodStart?.substring(0,10) }}~{{scope.row.packingValidityPeriodEnd?.substring(0,10)}}
                </template>
                </el-table-column>
                <el-table-column property="agentName" label="客户" show-overflow-tooltip align="center"/>
                <el-table-column property="packingStatus" label="状态" width="80" align="center">  <!--提箱单状态:  5-已发放 10-已下载 15-提箱中 20-已完成 25-作废 30-已过期-->
                <template #default="scope">
                    <template v-if="scope.row.packingStatus == 5">已发放</template>
                    <template v-if="scope.row.packingStatus == 10">已下载</template>
                    <template v-if="scope.row.packingStatus == 15">提箱中</template>
                    <template v-if="scope.row.packingStatus == 20">已完成</template>
                    <template v-if="scope.row.packingStatus == 25">作废</template>
                    <template v-if="scope.row.packingStatus == 30">已过期</template>
                    <template>--</template>
                </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 提箱单信息 -->
        <tixiangdanInfo ref="tixiangdanInfoRef" @tixiangdanInfoClick="txClick"  @tixiangdanInfoListClick="txListClick"></tixiangdanInfo>
    </div>
</template>
<script lang="ts" setup>
import { ref,reactive, onMounted,computed, getCurrentInstance } from 'vue'
import  Carousel from '@/components/carousel'
import invoiceTemplate from '@/views/components/invoiceTemplate.vue'
import Steps from "@/views/placingOrder/tradeOrder/component/steps"
import StepsTool from "@/views/placingOrder/tradeOrder/component/steps-tool"
import Signature from '@/views/placingOrder/tradeOrder/component/signature'
import ImgUpload from '@/components/upload/uploadFiles-Images.vue'
import { useRoute,useRouter } from 'vue-router'
import { updatePurchaseBoxOrder,getOrderInfo,cancelPurchaseBoxOrderById,boxEastPackingListPage } from '@/api/boxDeal/boxBuy'
import { processApproved, processRejected } from '@/api/orderCheck/index'
import { addRentRequestInvoice, rentUploadingInvoice, addPurchaseBoxRequestInvoice } from '@/api/invoice'
import { getEqbContractOrderInfo } from '@/api/contract/eQianBao'
import { ElMessage, ElLoading,ElMessageBox } from 'element-plus'
import  basicConfig from '@/constant/containerInfo'
import { userSimpleList } from '@/api/user/index'
import { getPackingData,rentBoxList } from '@/api/orderManage/packing'
import { addPackingBoxSell } from '@/api/boxDeal/tiXiangManage'
import tixiangdanInfo from '@/views/components/order/tixiangdanInfo';
import Cookies from 'js-cookie'
import { formatDate } from '@/utils'
import { Edit } from '@element-plus/icons-vue'

const radioView = ref(false)
const route = useRoute()
const router = useRouter()
const companyRole = localStorage.getItem('companyRole')
const sourceType = computed(()=>{
    return route.query.sourceType // view：查看页面 edit：编辑页面
}) 

const businessRoleEnum = computed(()=>{
    return route.query.businessRoleEnum //公司类型: 5-买箱公司 10-卖箱公司
}) 
// const processBusinessType = ref(8) // 订单审核流程 5-出口箱审核 8-出口箱非管理员审核 20-出口箱箱东取消订单 25-出口箱货代取消订单
// const currentNodeType = ref(5) // 订单节点 出口箱:5-货代操作员提交 10-箱东操作员确认 30-E签宝签章


const paymentMethod = ref("5")
const _stepStatus = ref(2) // 当前订单状态 
const _cancellationStatus = ref(0) // 取消订单时的订单状态 [只有_stepStatus == 35 时 此参数才有效]
const _frontNodeReviewStatus = ref(0) // 上一个节点审核结果 5-通过 10-驳回
const _currentNodeType =  ref(0) // 订单节点
const rowData = ref({ // 订单基本信息
    id:'',
    orderNo:'',
    companyName:'',
    carryCityName:'',
    carryCountryName:'',
    areaCode:'86',
    publisherName:'',
    publisherTel:'',
    unitPrice:'',
    currency:'',
    boxType:'',
    boxCondition:'',
    amount:'',
    boxQuantity:'',
    contacts:'',
    tel:'',
    planPickupDate:'',
    period:'',
    leaveMsg:'',
    processId:'',
    boxEastOperatorUserName:'',
    companyId:'',
    remark:'',
    packingAllocationQuantity:'',
    invoiceStatus:'5',  // # invoiceStatus; 发票状态 5-未申请 10-待开票 15-已开票
    invoiceType: '5',
    canceledType:'', //取消类型(5-箱东取消 10-货代取消)	
    releaseSaleId:'',
    containerNo:''	
}) 
const total  = computed(()=>{ 
    const quantity = Number(rowData.value.boxQuantity) || 0
    const price = Number(rowData.value.unitPrice) || 0
    return (quantity * price).toFixed(2) // 保留两位小数，根据业务需要可调整
})
const rules = { 
    invoiceType:[
        { required: true, message: '发票类型必选', trigger: 'blur' }
    ],
    invoiceTitle:[
        { required: true, message: '企业名称必填', trigger: 'blur' },
        { pattern:/^[a-zA-Z\u4e00-\u9fa5]*$/, message: "只能输入英文和汉字", trigger: "blur" },
    ],
    invoiceTaxNum:[
        { required: true, message: '统一社会信用代码必填', trigger: 'blur' },
        { pattern:/^[0-9a-zA-Z]*$/, message: "只能输入数字和英文", trigger: "blur" },
    ]
}
interface UserSimple {
  userId: string | number
  nickname: string
}
const param = reactive({ 
    boxEastOperatorUserId:0, //操作员ID
    userSimpleList:[] as UserSimple[],
    packingInfo:[{
        id:'',
        orderNo:'',
        planPickupDate:'',
        createTime:'',
        packingAllocationQuantity:'',
        boxQuantity:'',
        needPackingNum:''
    }],
    containerNo:''
})

// param.boxEastOperatorUserId = computed(()=>{
//   let nickName = JSON.parse(Cookies.get("User-Info"))?.nickname;
//   return getOperatorUserId(nickName)
// })

const allocation = ref([
    {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId: '',            // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
])
const orderInfo = async() =>{ // 获取订单详情
    if(!route.query.orderId) return ElMessage.warning('参数错误,请返回上一级并刷新页面')
    await getOrderInfo(route.query.orderId).then((res:any)=>{ 
        if(res.code == '00000'){
            rowData.value = res.data
            _stepStatus.value = res.data.status
            _cancellationStatus.value = res.data?.cancellationStatus || 0
            _frontNodeReviewStatus.value = res.data?.frontNodeReviewStatus || 0
            _currentNodeType.value = res.data?.currentNodeType || 0
            paymentMethod.value = res.data.paymentMethod.toString()
            // _stepStatus.value = 10
            swiperData.list = res.data.mainFileList? JSON.parse(res.data?.mainFileList) : []
            param.packingInfo.length = 0
            let packingItem = {
                id: res.data.id,
                orderNo: res.data.orderNo,
                planPickupDate:res.data.planPickupDate,
                createTime:res.data.createTime,
                packingAllocationQuantity: res.data.packingAllocationQuantity,
                boxQuantity: res.data.boxQuantity,
                needPackingNum: res.data.boxQuantity - res.data.packingAllocationQuantity,
                boxType:res.data.boxType,
                boxCondition:res.data.boxCondition,
                carryCityId:res.data.carryCityId,
                returnCityId:res.data.returnCityId

            }
            param.packingInfo.push(packingItem)
            try{ 
                allocation.value = JSON.parse(res.data.allocation) 
            }catch(e){

            }
        }
    })

}

const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
  }
})


onMounted(()=>{ 
    orderInfo()
    userSimpleList({}).then(res=>{ 
        if(res.code == '00000' && res.data.length > 0){
            param.userSimpleList = res.data
            localStorage.setItem('userSimpleList', JSON.stringify(res.data))

            let nickName = JSON.parse(Cookies.get("User-Info"))?.nickname;
            param.boxEastOperatorUserId = Number(getOperatorUserId(nickName))
        }    
    })
  
})

const toCancelOrder = () =>{ //货代取消租箱订单
    ElMessageBox.prompt('请输入订单取消原因', '提示', {
        confirmButtonText: '确认取消',
        cancelButtonText: '暂不取消',
        inputType: 'textarea', // 使用多行文本输入
        inputPlaceholder: '请输入取消原因...',
        inputValidator: (value) => {
            // 验证逻辑
            if (!value || value.trim() === '') return '取消原因不能为空！'; // 必填校验
            if (value.length > 500) return '取消原因不能超过500字符！'; // 长度校验
            return true; // 验证通过
        },
        inputErrorMessage: '请输入有效的取消原因', // 通用错误提示
    }).then(async({ value }) => {
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        let reqInfo = {
            id: rowData.value.id,
            remark: value
        };

        try {
            const res: any = await cancelPurchaseBoxOrderById(reqInfo);
            if (res.code == "00000") {
                ElMessage.warning("申请取消订单取消成功");
                let pathUrl = ''
                 if(businessRoleEnum.value == '5'){
                  if(companyRole=='zx'){ //货代
                    pathUrl = '/hdzxgm/agentBuyOrder'
                }else if(companyRole=='putBox'){
                    pathUrl = '/xdzxgm/agentBuyOrder';
                }
                }else if(businessRoleEnum.value == '10'){
                    pathUrl = '/xdzxcs/sellOrder'
                }
                router.replace({ path: pathUrl })
            }
        } catch (error) {
            ElMessage.error("取消失败");
        } finally {
            loading.close();
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消操作',
        })
    })
}
const isPass = ref(true)
const confirmOrder =  async()=>{ //箱东确认购箱订单
    if(_stepStatus.value == 2 && businessRoleEnum.value == '10'){
        if(!radioView.value){
            return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
        }
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    try { 
        let reqUpdate = {
            id: rowData.value.id,
            unitPrice: rowData.value.unitPrice,
            currency: rowData.value.currency,
            // containerNo:formattedContainer(param.containerNo),
            boxEastOperatorUserId: param.boxEastOperatorUserId,
            boxEastOperatorUserName: getOperatorUserName(param.boxEastOperatorUserId),
            boxQuantity:rowData.value.boxQuantity,
            paymentMethod:paymentMethod.value,
            period:rowData.value.period,
            rate:'',
            couponAmount:'',
            planPickupDate:rowData.value.planPickupDate
        }
        if (!isPass.value) return ''
        await updatePurchaseBoxOrder(reqUpdate).then((res:any) => { 
            loading.close()
            if(res.code === "00000"){
                ElMessage({ message: '订单确认成功', type: 'success' })
                router.push({
                    path:'/xdzxcs/sellOrder',
                    query:{
                        tag: new Date().getTime()
                    }
                })
            }
        })
        const data = { "processId": rowData.value.processId }
        await processApproved(data).then((res:any) => {
            loading.close()
        })
    } catch (error) {
        ElMessage.error('确认失败')
    }finally {
        loading.close(); // 无论如何都关闭 loading
    }
}

const formattedContainer = (containerNumber:string) =>{ //处理检查箱号
    isPass.value = true
    if(containerNumber){
        containerNumber =  containerNumber.replace(/\s/g, '') // 去掉所有空格  
        containerNumber =  containerNumber.replace(/\//g, ',')// 把所有中文逗号替换成英文逗号
        let containerNumberArr: string[]  = containerNumber.split(",")
        containerNumberArr.forEach((item,index) => {
            const regExp = /^[A-Z]{3}U\d{7}$/
            if(!regExp.test(item)){
                ElMessage({
                    type:'warning',
                    message:`请检查输入的第${index + 1}个箱号是否正确`,
                    duration:5000
                })
                isPass.value = false
            }
        })
        return containerNumber
    } 

    return containerNumber
}
const eqbDialog = ref(false)
const eqbUrl = ref('')
const signContract = async()=>{ //签署  
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const reqeQianBao = {
       orderId: rowData.value.id,
       businessType: 15  // 5:出口（租箱） 10：进口（回调） 15：购箱

    }
    await getEqbContractOrderInfo(reqeQianBao).then((res: any) => { 
        if(res.code == '00000'){
            eqbUrl.value = res.data.longContractUrl
        }
        loading.close()
        eqbDialog.value = true
    })
}


const getOperatorUserName = (id: string): string => {
    const user = param.userSimpleList.find(item => item.userId == id)
    return user ? user.nickname : ''
}
const getOperatorUserId = (name: string): string => {
    const user = param.userSimpleList.find(item => item.nickname == name)
    return user ? String(user.userId) : ''
}

const closeEQianBao = () => { //关闭e签宝 后刷新页面
    if(businessRoleEnum.value == '5'){ //买方
        if(companyRole=='zx'){ //货代
            router.push({ 
            path:'/hdzxgm/agentBuyOrder',
                query:{
                    tag: new Date().getTime()
                }
            });
        }else if(companyRole=='putBox'){
              router.push({ 
                path:'/xdzxgm/agentBuyOrder',
                query:{
                    tag: new Date().getTime()
                }
            });
        }
       
    }else if(businessRoleEnum.value == '10'){ // 出售方
        router.push({ 
            path:'/xdzxcs/sellOrder',
            query:{
                tag: new Date().getTime()
            }
        });
    }  
}

const { proxy } = getCurrentInstance()
const completeSigning = (id:any) => {  //完成签署
  let reqParam = { // 5:租箱 10：回调（进口） 15：购箱 
    orderId:id,
    businessType:15
  }
  proxy.$common(reqParam).then((res:any) => { 
    if(res.code == "00000"){
      ElMessage.success('操作成功')
    }else{
      ElMessage.warning(res.msg)
    }
  })
}

const dackingDialog = ref(false)
const packingListData = ref([])
const packingBoxType = ref([])
const packingValidityPeriod = ref([])
const fileList = ref([])
const packingRemark = ref()
const handlePacking = () => { // 开提箱单
    packingListData.value.length = 0
    let pakingInfo = {
        orderNo: rowData.value.orderNo,
        planPickupDate: rowData.value.planPickupDate,
        createTime:rowData.value.createTime
    }
    packingListData.value.push(pakingInfo)
    packingBoxType.value.length = 0
    let boxInfo = {
        boxType: rowData.value.boxType,
        boxCondition: rowData.value.boxCondition,
        boxQuantity:rowData.value.boxQuantity
    }
    packingBoxType.value.push(boxInfo)
    dackingDialog.value = true
}
const packingRef = ref()
const submitPicking = async() =>{ // 开提箱单
    // let orderInfo = [{
    //     orderId: rowData.value.id,
    //     orderNo: rowData.value.orderNo,
    //     planPickupDate: rowData.value.planPickupDate,
    //     createTime: rowData.value.createTime
    // }]
    const reqParam = {
        boxType:rowData.value.boxType,
        boxCondition: rowData.value.boxCondition,
        orderList: JSON.stringify(packingListData.value),
        packingValidityPeriodStart: packingValidityPeriod.value[0],
        packingValidityPeriodEnd: packingValidityPeriod.value[1],
        packingFileList: JSON.stringify(packingRef.value.fileList),
        remark:packingRemark.value
    }
    await addPackingBoxSell(reqParam).then(res => {
        if(res.code == "00000"){
            ElMessage.success("提箱单开具成功")
            router.push({
                path:"/xdzxcs/sellOrder"
            })
        }
    }).catch(error => {
        console.log(error)
    })
}
const closeDialog = () => {  // 关闭提箱单弹窗
    dackingDialog.value = false
}
const invoiceDialog = ref(false)
//申请发票
const invoiceRef = ref()
const applyInvoice = () => {
    invoiceRef.value.validate(valid =>{
        if (valid) { 
            const data = {
                invoiceOrder: JSON.stringify([{ orderId: rowData.value.id, orderNo: rowData.value.orderNo }]),
                invoiceTitle: rowData.value.invoiceTitle?.trim(),
                invoiceContent: "购箱明细",
                invoiceType: rowData.value.invoiceType,
                creditCode: rowData.value.invoiceTaxNum?.trim(),
                tel:rowData.value.tel
            }
            addPurchaseBoxRequestInvoice(data).then((res: any) => {
                if(res.code == '00000'){
                    ElMessage.success('申请开票成功，请等待卖方公司开具发票')
                    invoiceDialog.value= false
                    router.push({
                        path:'/xdzxgm/agentBuyOrder'
                    })
                }
              })
        }else{
            return false;
        }
    })
 
}

// 解约拒绝 
const rejected = () =>{
    ElMessageBox.prompt('请输入拒绝取消原因', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '关闭',
        inputType: 'textarea', // 使用多行文本输入
        inputPlaceholder: '请输入拒绝原因...',
        inputValidator: (value) => {
            // 验证逻辑
            if (!value || value.trim() === '') return '取消原因不能为空！'; // 必填校验
            if (value.length > 500) return '取消原因不能超过500字符！'; // 长度校验
            return true; // 验证通过
        },
        inputErrorMessage: '请输入有效的取消原因', // 通用错误提示
    }).then(async({ value }) => {
        const data = { "processId": rowData.value.processId,reviewRemark:value }
        processRejected(data).then((res:any) => {
            let pathUrl = ''
            if(businessRoleEnum.value == '5'){
                  if(companyRole=='zx'){ //货代
                    pathUrl = '/hdzxgm/agentBuyOrder'
                }else if(companyRole=='putBox'){
                    pathUrl = '/xdzxgm/agentBuyOrder';
                }
            }else if(businessRoleEnum.value == '10'){
                pathUrl = '/xdzxcs/sellOrder'
            }

            router.replace({ path: pathUrl })
        })

    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消操作',
        })
    })


}
// 解约确认 
const approved = (source:any) =>{
    const data = { "processId": rowData.value.processId }
    let message = '解约成功'
    if(source == 2){ // 2：拒绝解约时调用
        message = '订单未取消，重新检查该订单'      
    }
    processApproved(data).then((res:any) => {
        ElMessage({
            type: 'success',
            message: message,
        })
        let pathUrl = ''
         if(businessRoleEnum.value == '5'){
                if(companyRole=='zx'){ //货代
                    pathUrl = '/hdzxgm/agentBuyOrder'
                }else if(companyRole=='putBox'){
                    pathUrl = '/xdzxgm/agentBuyOrder';
                }
            }else if(businessRoleEnum.value == '10'){
                pathUrl = '/xdzxcs/sellOrder'
            }
        router.replace({ path: pathUrl })
    })
}



//查看提箱单
const packingListDialog = ref(false)
const packingListInfo = ref()
const showPackingList = ()=>{
    rentBoxList(rowData.value.id).then((res: any) => {
        packingListDialog.value = true
        packingListInfo.value = res.data

  }).catch((err: any) => {
    ElMessage.warning("提箱单列表查询失败，请稍后再试")
  })
}
//提箱单详情
const tixiangdanInfoRef = ref()
const showPacking = async (val:any) => {
packingListDialog.value = false
  if (!val.packingId) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  tixiangdanInfoRef.value.openBox(val.packingId)
}

const orderListDialog = ref(false)
const orderListInfo = ref([])
const selectedInfo = ref([]) //选中的订单列表
// 选中订单列表
const getOrderList = async() => { 
    const data = {
        pageNum: 1,
        pageSize: 200,
        boxType: rowData.value.boxType,
        boxCondition:rowData.value.boxCondition,
        carryCityId: rowData.value.carryCityId,
        agentUserId: rowData.value.agentUserId,
        sortBeans: [{ "field": "createTime", "isAsc": "asc" }] // desc 降序  asc 升序
    }
    await boxEastPackingListPage(data).then((res: any) => { 
        if(res.code == '00000' && res.data){
            orderListInfo.value.length = 0
            res.data.list.forEach(item =>{
                if(item.orderNo != rowData.value.orderNo){
                    orderListInfo.value.push(item)
                }
            })
            orderListDialog.value = true
        }else{
            ElMessage.warning("订单列表查询失败，请稍后再试")
        }
    }).catch((err: any) => {
      ElMessage.warning("订单列表查询失败，请稍后再试")
    })
}

const submitOrderInfo = () => {
    packingListData.value.length = 0
    const pakingThe = {
        orderId:rowData.value.id,
        orderNo: rowData.value.orderNo,
        planPickupDate: rowData.value.planPickupDate,
        createTime:rowData.value.createTime
    }
    packingListData.value.push(pakingThe)
    selectedInfo.value.forEach(item => {
        const pakingInfo = {
            orderId: item.id,
            orderNo: item.orderNo,
            planPickupDate: item.planPickupDate,
            createTime:item.createTime
        }
        packingListData.value.push(pakingInfo)
    })
    orderListDialog.value = false
}
const handleSelectionChange = (select:[]) =>{
    selectedInfo.value = select
    console.log(selectedInfo.value)
}
</script>
<style lang="scss" scoped>
.city-title{
    font-weight: 500;
    font-size: 18px;
}
.city-content{
    color: #999;
}
.input-with-select{
    color: #ff0000;
}
.total{
    color: #ff0000;
    font-size: 24px;
    font-weight: 600;
}
.signature-position{
    position: absolute;
    top: 0;
    right: 0;
}
</style>